package com.ophiux.wechat.utils;

import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * XML 文档解析取值
 * @author Administrator
 *
 */
public class XmlUtil {
	
	private static XmlUtil xmlUtil;
	
	public static XmlUtil getInstance(){
		if(xmlUtil == null){
			xmlUtil = new XmlUtil();
		}
		return xmlUtil;
	}  
	
	public String getValue(String xml,String key){
		
		// xml文档
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = null;
		
		try {
			db = dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		
		// 解析xml
		InputSource eris = new InputSource(new StringReader(xml));
		Document erDocument = null;
		try {
			erDocument = db.parse(eris);
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Element root = erDocument.getDocumentElement();
		NodeList nodeEncrypt = root.getElementsByTagName(key);
		String value = nodeEncrypt.item(0).getTextContent();
		
		return value;
		
	}
	
	/**
	 * 将Map转换为Xml字符串
	 * Map的键与xml的节点名一致
	 * @param map
	 */
	public String mapToXml(HashMap<String,String> map){
		
		if(map == null){
			return "";
		}
		StringBuffer xmlStr = new StringBuffer( "<xml>");
		for(String key:map.keySet()){
			String value = map.get(key);
			xmlStr = buildXml(xmlStr, key, value);
		}
		xmlStr.append("</xml>");
		return xmlStr.toString();
	}
	
	/**
	 * 组装xml
	 * @param xmlStr  数据源xml
	 * @param nodeName   待组装xml节点名
	 * @param value      待组装xml值
	 * @return 组装后的xml
	 */
	public StringBuffer buildXml(StringBuffer xmlStr,String nodeName,String value){
		
		xmlStr.append("<"+nodeName+">").append(value).append("</"+nodeName+">");
		return xmlStr;
	}
	
}